import router from './router'
import store from './store'
import { Message } from 'element-ui'
import NProgress from 'nprogress' // progress bar
import 'nprogress/nprogress.css' // progress bar style
import { getUserInfo } from '@/utils/auth' // get token from cookie
import getPageTitle from '@/utils/get-page-title'

NProgress.configure({ showSpinner: false }) // NProgress Configuration

// const whiteList = ['/login'] // no redirect whitelist

router.beforeEach(async(to, from, next) => {
  // start progress bar
  NProgress.start()

  // set page title
  document.title = getPageTitle(to.meta.title)

  if (to.path === '/login') {
    // if is logged in, redirect to the home page
    next()
    NProgress.done()
  } else {
    // determine whether the user has obtained his permission roles through getInfo
    const roles = JSON.parse(getUserInfo()).user_type
    const isSuperAdmin = JSON.parse(getUserInfo()).user_type === 'SUPER_ADMIN'
    const hasRoles = JSON.parse(getUserInfo()).user_type === to.meta.roles
    console.log(JSON.parse(getUserInfo()).user_type)
    // console.log(hasRoles)

    const accessRoutes = await store.dispatch('permission/generateRoutes', roles)
    router.addRoutes(accessRoutes)

    if (isSuperAdmin) {
      next()
    } else if (hasRoles) {
      next()
      // next({ ...to, replace: true })
    } else {
      Message.error('您暂无权限进入此页！')
      next(false)
      NProgress.done()
    }
  }
})

router.afterEach(() => {
  // finish progress bar
  NProgress.done()
})
